package br.com.linkideias.controller;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import br.com.linkideias.util.HibernateUtil;

public class FiltroTransacaoHibernate implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain fc) throws IOException, ServletException {
		Session session = null;
		System.out.println("Estou no filtro");
		
		try {
			
			session = HibernateUtil.getSessionFactory().openSession();
			
			session.beginTransaction();
			((HttpServletRequest) request).setAttribute(HibernateUtil.HIBERNATE_SESSION, session);fc.doFilter(request, response);
			session = (Session) ((HttpServletRequest) request).getAttribute(HibernateUtil.HIBERNATE_SESSION);
			session.flush();
			session.getTransaction().commit();
			
		} catch (HibernateException e) {
			session.getTransaction().rollback();
			System.out.println(e.toString());
			e.printStackTrace();
		}finally
		{
		if (session != null && session.isOpen()) {
			session.flush();
			session.close();
		}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
